#!/bin/bash
#完全备份多个数据库
#获取当前时间
date_now=$(date "+%Y%m%d-%H%M%S")
host=127.0.0.1
port=8848
username=root
password=root
#要备份的多个数据库名
db_name1=db1
db_name2=db2
#备份的路径
BACKUP=/data/mysql_bak/backup_data
#当前的时间作为文件名
DATETIMEFile=$(date +%Y_%m_%d)
DATETIME=$(date +%Y_%m_%d_%H)
#创建备份的路径
#如果备份的路径文件夹存在就使用，否则创建
[ ! -d "$BACKUP/$DATETIMEFile"  ]  && mkdir -p "$BACKUP/$DATETIMEFile" 
echo "${date_now}">> ${BACKUP}/mysqllog.log
echo "==========START BACKUP==========="
echo "backupPath: $BACKUP/$DATETIMEFile/${DATETIME}_${db_name1}_${db_name2}.sql"
fileName="$BACKUP/$DATETIMEFile/${DATETIME}_${db_name1}_${db_name2}.sql"
mysqldump  -h${host}  -P7360  -u${username} -p${password}   --column-statistics=0 --ssl-mode=DISABLED  --single-transaction --skip-triggers --skip-lock-tables --master-data=2 --force    -B ${db_name1}  ${db_name2}>$BACKUP/$DATETIMEFile/${DATETIME}_${db_name1}_${db_name2}.sql  2>> ${BACKUP}/mysqllog.log
#mysqldump  -h${host}  -P7360  -u${username} -p${password}  --ssl-mode=DISABLED  --single-transaction --skip-triggers --skip-lock-tables --master-data=2 --force    -B ${db_name1}  ${db_name2}>$BACKUP/$DATETIMEFile/${DATETIME}_${db_name1}_${db_name2}.sql  2>> ${BACKUP}/mysqllog.log
#若备份成功则进行进行数据压缩
if [ "$?" == 0 ];then
cd $BACKUP/$DATETIMEFile
#将数据压缩节省存储空间
tar  zcvPf  ${fileName}.tar  ${fileName}
#tar  zcvf  ${fileName}.tar  ${fileName}
#删除临时目录
rm -rf  "$BACKUP/$DATETIMEFile/${DATETIME}_${db_name1}_${db_name2}.sql"
#删除30天前的备份文件(-exec rm -rf {} \是固定写法，删除查询出来的数据)
find $BACKUP -name "*.tar.gz" -type f -mtime +30 -exec rm -rf {} \; > /dev/null 2>&1
echo "-----SUCCESS BCAKUP MYSQL DATABASES ${db_name_one}-----"
else
#否则，备份失败则进行以下操作
#删除临时目录
rm -rf  "$BACKUP/$DATETIMEFile/${DATETIME}_${db_name1}_${db_name2}.sql"
echo "-----FAIL BACKUP  MYSQL DATABASES ${db_name_one}-----"
fi
echo ${date_now}>> ${BACKUP}/mysqllog.log
